<?php
namespace addons\ypsms\library;

use fast\Http;

class Ypsms
{

    private $_params = [];
    public $error = '';
    protected $config = [];
    protected static $instance;

    public function __construct($options = [])
    {
        if ($config = get_addon_config('ypsms')) {
            $this->config = array_merge($this->config, $config);
        }
        $this->config = array_merge($this->config, is_array($options) ? $options : []);
    }

    /**
     * 单例
     * @param array $options 参数
     * @return Hwsms
     */
    public static function instance($options = [])
    {
        if (is_null(self::$instance)) {
            self::$instance = new static($options);
        }

        return self::$instance;
    }

    /**
     * 设置参数
     * @param array $param
     * @return Hwsms
     */
    public function param(array $param = [])
    {
        foreach ($param as $k => &$v) {
            $v = (string)$v;
            $this->_params[$k] = $v;
        }
        unset($v);
        return $this;
    }

    /**
     * 接收手机
     * @param string $mobile 手机号码
     * @return Hwsms
     */
    public function mobile($mobile = '')
    {
        $this->_params['phone'] = $mobile;
        return $this;
    }

    public function send()
    {
        $url = $this->config['apiurl'];

        $this->error = '';
        $params = $this->_params();
        $ret = Http::post($url,$params);

        if ($ret) {
            $res = (array)json_decode($ret, true);
            if (isset($res['code']) && $res['code'] == '00000') {
                return true;
            }

            if (isset($res['success']) && $res['success'] == 1){
                return true;
            }

            if (isset($res['status']) && $res['status'] == true){
                return true;
                //$this->error = 'Api Times not reset';
            }
            $this->error = isset($res['desc']) ? $res['desc'] : 'Invalid result';
        } else {
            $this->error = 'Network error';
        }

        //if (config('app_debug')) {
            \think\Log::record('ypsms:' . $this->error);
        //}
        return false;
    }

    /**
     * 获取错误信息
     * @return string
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * 获取发送的参数信息
     * @return array
     */
    private function _params()
    {
        $params = $this->_params;

        //TODO 接口参数处理
        $arr = [];
        foreach ($params as $k => $v){
            $arr[] = $k . '='. $v;
        }

        $params = implode('&',$arr);

        //TODO 批量发送
        /*if (isset($params['to']) && $params['to']) {
            $toArr = explode(',', $params['to']);
            foreach ($toArr as $index => &$item) {
                if (substr($item, 0, 1) !== '+') {
                    $item = '+86' . $item;
                }
            }
            $params['to'] = implode(',', $toArr);
        }*/
        return $params;
    }

}